package org.sauceggplant.item.man.ui.frame;

import org.sauceggplant.item.man.ui.constant.Constants;
import org.sauceggplant.item.man.ui.panel.MainPanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.reflect.Method;
import java.util.Properties;

public class MainFrame extends JFrame {

    private static final Logger logger = LoggerFactory.getLogger(MainFrame.class);

    public static Properties PROPERTIES = new Properties();

    static {
        InputStream inputStream = MainFrame.class.getResourceAsStream("/ui.properties");
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(MainFrame.class.getName(), e);
        }
        try {
            PROPERTIES.load(inputStreamReader);
        } catch (IOException e) {
            logger.error(MainFrame.class.getName(), e);
        }
    }

    public MainFrame() {
        init();
    }

    private void init() {
        this.setTitle(PROPERTIES.getProperty(Constants.TITLE));
        Image icon = null;
        try {
            icon = ImageIO.read(this.getClass().getResourceAsStream("/icon.png"));
            this.setIconImage(icon);
            trySetMacOsDockIcon(icon);
        } catch (IOException e) {
            logger.error("主窗口加载图标失败", e);
        }
        initComponent();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        int width = Integer.valueOf(PROPERTIES.getProperty(Constants.WIDTH));
        int height = Integer.valueOf(PROPERTIES.getProperty(Constants.HEIGHT));
        double maxWidth = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        double maxHeight = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        //设置大小
        this.setSize(width, height);
        //屏幕居中
        this.setLocation((int) ((maxWidth - width) / 2), (int) ((maxHeight - height) / 2));
        this.setVisible(true);
    }

    private boolean trySetMacOsDockIcon(Image image) {
        try {
            Class<?> c = Class.forName("com.apple.eawt.Application");
            Method method = c.getMethod("getApplication");
            Object application = method.invoke(null);
            method = application.getClass().getMethod("setDockIconImage", Image.class);
            method.invoke(application, image);
            return true;
        } catch (Exception e) {
            logger.error("系统设置Dock图标失败", e);
            return false;
        }
    }

    private void initComponent() {
        MainPanel mainPanel = new MainPanel(this);
        this.getContentPane().add(mainPanel);
    }

    public static Properties getPROPERTIES() {
        return PROPERTIES;
    }
}

